<template>
  <base-modal :show.sync="serviceDialog" :title="titleText" width="600px" @close="handleClose">
    <form-builder v-if="serviceDialog" ref="formRef" :fields="fields" :value="form" @update="update">
      <template slot="svcSerialNumber" slot-scope="{ field, value }">
        <form-item :label="field.displayName">
          <form-text :field="field" :value="getWarrantyServiceItemLabel(value)" />
        </form-item>
      </template>

      <template slot="svcProjectName" slot-scope="{ field, value }">
        <form-item :label="field.displayName">
          <el-row type="flex" justify="space-between" :gutter="10">
            <biz-form-remote-select :field="field" v-model="selectedProductService" :remote-method="searchProductService" @input="updateProductService" :placeholder="$t('common.placeholder.select')" v-if="type == 'new'">
              <div class="product-template-option" slot="option" slot-scope="{ option }">
                <h3>{{ option.label }}</h3>
                <div class="product-item">
                  <div v-for="item in subFields" :key="item.fieldName" class="product_item_sub">
                    <label>{{ item.displayName }}：</label>
                    <span>{{ getWarrantyServiceItemLabel(option[item.fieldName]) }}</span><serviceProjectNameTag v-if="item.fieldName === 'svcProjectName' && option.system"/>
                  </div>
                </div>
              </div>
            </biz-form-remote-select>

            <el-input :value="getWarrantyServiceItemLabel(value)" disabled v-else></el-input>
            <el-button type="primary" icon="el-icon-plus" :style="{ marginLeft: '10px' }" @click="jumpServiceItem">{{ $t('product.addService') }}</el-button>
          </el-row>
        </form-item>
      </template>

      <!-- 默认服务项目周期 -->
      <template slot="serviceProjectCycle" slot-scope="{ field }">
        <form-item :label="field.displayName">
          <div :style="{ display: 'flex' }">
            <form-number :field="field" :value="form.timeLimit" :style="{ flex: 1 }" @input="updateServiceProjectCycle"></form-number>

            <el-select v-model="form.timeUnit" :style="{ marginLeft: '10px' }">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </div>
        </form-item>
      </template>

      <template slot="svcStartTime" slot-scope="{ field, value }">
        <form-item :label="field.displayName">
          <form-date :field="field" :value="value" @input="updateStartTime"></form-date>
        </form-item>
      </template>

      <template slot="svcEndTime" slot-scope="{ field, value }">
        <form-item :label="field.displayName">
          <form-date :field="field" :value="value"></form-date>
        </form-item>
      </template>
    </form-builder>

    <div slot="footer">
      <el-button @click="handleClose">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t('common.base.confirm') }}</el-button>
    </div>
  </base-modal>
</template>
<script>
import { defineComponent, ref, computed, reactive, toRefs, set } from 'vue';
import moment from 'moment';

import { subFields, periodOption } from '@src/modules/productV2/productWarrantyServiceItem/productWarrantyItemListPage/fields.js';

import { productQualityManageList } from '@src/api/ProductV2Api.js';

import { toast } from '@src/util/platform';

import i18n from '@src/locales';
import appConfig from 'app.config';

import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import serviceProjectNameTag from '@src/modules/setting/productV2/productQualityManagement/serviceProjectNameTag.vue';
import { WarrantyServiceItemLabelEnum } from '@model/enum/LabelEnum'

export default defineComponent({
  name: '',
  components: {
    serviceProjectNameTag,
  },
  props: {
    columnFields: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: 'new',
    },
  },
  emits: ['handleSubmit'],
  setup(props, { emit }) {
    const formRef = ref();

    const state = reactive({
      serviceDialog: false,
      fields: [],
      subFields: [...subFields()],
      form: {
        svcStartTime: '',
        svcEndTime: '',
      },
      selectedProductService: [],
      options: periodOption,
    });

    const titleText = computed(() => {
      const titleMap = {
        new: i18n.t('product.addService'),
        edit: i18n.t('product.editService'),
      };
      return titleMap[props.type];
    });

    // 打开弹框
    const openDialog = () => {
      state.serviceDialog = true;
      state.fields = props.columnFields;
    };

    // 确认
    const handleSubmit = async () => {
      const validateRes = await formRef.value.validate(false);
      if (!validateRes) return;

      const params = {
        ...state.form,
        svcStartTime: moment(state.form?.svcStartTime).valueOf(),
        svcEndTime: moment(state.form?.svcEndTime).valueOf(),
      };
      emit('handleSubmit', params);
    };

    // 取消
    const handleClose = () => {
      handleReset();
    };

    // 搜索服务项目
    const searchProductService = (params = {}) => {
      return productQualityManageList({
        ...params,
        enabled: true
      }).then(res => {
        const { success, message, result } = res || {};

        if (!success) return toast(message, 'error');

        result.list = result.list.map(item =>
          Object.freeze({
            label: getWarrantyServiceItemLabel(item?.svcProjectName) || '',
            value: item?.id || '',
            ...item,
          })
        );

        return result;
      });
    };

    /* form-builder更新事件 */
    const update = ({ field, newValue, oldValue }) => {
      let { fieldName, displayName } = field;
      if (appConfig.debug) {
        console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }
      set(state.form, fieldName, newValue);
    };

    // 选择服务项目
    const updateProductService = val => {
      const newVal = val[0];

      state.form = {
        svcStartTime: '',
        svcEndTime: '',
        ...newVal,
      };
    };

    // 更新开始时间
    const updateStartTime = val => {
      state.form.svcStartTime = val;

      autoCalculateEndDate(val);
    };

    const updateServiceProjectCycle = val => {
      state.form.timeLimit = val;
    };

    // 自动计算结束日期/*  */
    const autoCalculateEndDate = startVal => {
      const { timeUnit, timeLimit } = state.form;

      state.form.svcEndTime = moment(startVal).add(timeLimit, timeUnit).subtract(1, 'day').format('YYYY-MM-DD');
    };

    const handleReset = () => {
      state.serviceDialog = false;
      state.selectedProductService = [];
      state.form = {
        svcStartTime: '',
        svcEndTime: '',
      };
    };

    // 跳转新建服务
    const jumpServiceItem = () => {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductQualityManagement,
      });
    };

    // 获取质保服务项目的多语言label
    const getWarrantyServiceItemLabel = (label) => {
      return WarrantyServiceItemLabelEnum[label] || label
    }

    return {
      formRef,
      ...toRefs(state),
      titleText,
      openDialog,
      handleSubmit,
      handleClose,
      update,
      searchProductService,
      updateProductService,
      updateStartTime,
      updateServiceProjectCycle,
      jumpServiceItem,
      handleReset,
      getWarrantyServiceItemLabel,
    };
  },
});
</script>
<style lang="scss" scoped>
.product-template-option {
  font-size: 12px;
  padding: 10px 0;
  h3 {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 24px;
    margin-bottom: 0;
  }
  .product_item {
    &_sub {
      line-height: 24px;
    }
    .customer-unbind-name {
      color: #bfbfbf;
    }
  }
}
</style>
